Client
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client implements Runnable {
static Thread t1, t2;
static Socket s;
static BufferedReader br1, br2;
static PrintWriter pr;
public void run() {
try {
if (Thread.currentThread() == t1) {
while (true) {
String str1 = br1.readLine();
System.out.println("Client says : "+str1);
pr.println(str1);
pr.flush();
if (str1.equals("bye")) {
break;
}
}
}
if (Thread.currentThread() == t2) {
while (true) {
String str2 = br2.readLine();
if (str2.equals("bye")) {
System.out.println("Server says : "+str2);
break;
} else {
System.out.println("Server says : "+str2);
}
}
}
} catch (IOException ex) {
}
}
public static void main(String[] args) throws UnknownHostException, IOException {
s = new Socket("localhost", 1234);
br1 = new BufferedReader(new InputStreamReader(System.in));
br2 = new BufferedReader(new InputStreamReader(s.getInputStream()));
pr = new PrintWriter(s.getOutputStream());
t1 = new Thread(new TestCl());
t1.start();
t2 = new Thread(new TestCl());
t2.start();
}
}
Output:
Server says : hai
hello
Client says : hello
Server says : bye
bye
Client says : bye